'use strict';
const db = uniCloud.database();

exports.main = async (event, context) => {
  console.log('【getNotificationMessages】云函数被调用，event：', event);

  const { userId, type, limit = 20 } = event;

  if (!userId) {
    return { success: false, message: '用户ID缺失' };
  }
  
  try {
    // 构建查询条件
    let whereCondition = {
      user_id: userId,
      status: 'active'
    };

    // 如果指定了类型，添加类型过滤
    if (type && type !== 'all') {
      whereCondition.type = type;
    }

    // 查询通知消息
    const res = await db.collection('notification-messages')
      .where(whereCondition)
      .orderBy('create_time', 'desc')
      .limit(limit)
      .get();

    console.log('【getNotificationMessages】查询结果：', res);

    return {
      success: true, 
      data: res.data, 
      message: '查询成功' 
    };

  } catch (e) {
    console.error('【getNotificationMessages】异常:', e);
    return { success: false, message: '查询失败：' + e.message };
  }
};
